import { useState, useCallback } from 'react';
import { message } from 'antd';
import { Message, MessageStats } from '../types/Message';
import { MessageFilters } from '../types/SharedTypes';
import { api, ApiError } from '../utils/api';
import { MESSAGES, PAGINATION_CONFIG } from '../constants/api';
import { getPaginationSize, savePaginationSize } from '../utils/storage';

export const useMessages = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  
  // 从localStorage获取保存的分页大小
  const savedPageSize = getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE);
  
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: savedPageSize,
    total: 0,
    totalPages: 0,
  });
  const [stats, setStats] = useState<MessageStats | null>(null);

  // 获取消息列表
  const fetchMessages = useCallback(async (filters: MessageFilters = {}) => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams();
      
      if (filters.roomId) queryParams.append('roomId', filters.roomId);
      if (filters.startTime) queryParams.append('startDate', filters.startTime);
      if (filters.endTime) queryParams.append('endDate', filters.endTime);
      if (filters.sessionId) queryParams.append('sessionId', filters.sessionId);
      if (filters.page) queryParams.append('page', filters.page.toString());
      
      // 使用保存的分页大小或过滤器中的大小
      const pageSize = filters.limit || pagination.pageSize;
      console.log('请求使用的分页大小:', pageSize); // 调试日志
      queryParams.append('limit', pageSize.toString());

      // 判断是否是礼物消息类型
      const isGiftMessage = filters.type === 'WebcastGiftMessage';
      
      // 根据消息类型决定使用哪个API
      let url = '';
      if (isGiftMessage) {
        // 使用礼物API
        url = `/api/gifts${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
      } else {
        // 使用消息API
        if (filters.type) queryParams.append('messageType', filters.type);
        url = `/api/messages${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
      }
      
      const response = await api.get(url) as {
        success: boolean;
        data: any[] | { items: any[], pagination: any };
        pagination?: {
          current?: number;
          page?: number;
          pageSize?: number;
          limit?: number;
          total: number;
          totalPages: number;
        };
      };
      
      if (response.success) {
        let items: any[] = [];
        let paginationData: any = {};
        
        // 处理不同API返回的数据结构
        if (isGiftMessage && 'items' in response.data) {
          // 礼物API返回格式
          items = response.data.items;
          paginationData = response.data.pagination;
        } else if (Array.isArray(response.data)) {
          // 消息API返回格式
          items = response.data;
          paginationData = response.pagination || {};
        }
        
        // 映射API返回的字段到前端期望的字段
        const mappedMessages = items.map((item: any) => {
          if (isGiftMessage) {
            // 礼物数据映射到消息格式
            const giftName = item.gift?.name || '未知礼物';
            const giftPrice = item.gift?.price || 0;
            const giftIcon = item.gift?.icon;
            
            return {
              id: item.id,
              roomId: item.roomId,
              userId: item.userId,
              sessionId: item.sessionId,
              messageType: 'WebcastGiftMessage',
              content: `送出礼物：${giftName}`,
              giftName: giftName,
              giftCount: item.quantity,
              giftValue: giftPrice * item.quantity, // 计算总价值
              giftIcon: giftIcon,
              userName: item.userName,
              userAvatar: item.userAvatar,
              userGender: item.userGender,
              payGrade: item.payGrade,
              fansLevel: item.fansLevel,
              fansClubName: item.fansClubName,
      
              createdAt: item.createdAt,
              type: 'WebcastGiftMessage',
              timestamp: item.createdAt
            };
          } else {
            // 普通消息映射
            return {
              ...item,
              type: item.messageType, // 将messageType映射为type
              timestamp: item.createdAt // 将createdAt映射为timestamp
            };
          }
        });
        
        setMessages(mappedMessages);
        
        // 获取分页大小 - 优先使用请求中指定的大小
        const newPageSize = filters.limit || paginationData?.pageSize || paginationData?.limit || 20;
        console.log('设置新的分页大小:', newPageSize); // 调试日志
        
        // 映射后端分页字段到前端状态
        setPagination({
          current: paginationData?.current || paginationData?.page || 1,
          pageSize: newPageSize,
          total: paginationData?.total || 0,
          totalPages: paginationData?.totalPages || 0
        });
        
        // 保存分页大小到localStorage
        savePaginationSize(newPageSize);
      } else {
        message.error('获取消息列表失败');
      }
    } catch (error) {
      console.error('获取消息列表错误:', error);
      if (error instanceof ApiError) {
        message.error(`获取消息列表失败: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
    } finally {
      setLoading(false);
    }
  }, [pagination.pageSize]);

  // 获取消息统计
  const fetchMessageStats = useCallback(async (filters: Omit<MessageFilters, 'page' | 'limit'> = {}) => {
    try {
      const queryParams = new URLSearchParams();
      
      if (filters.roomId) queryParams.append('roomId', filters.roomId);
      if (filters.type) queryParams.append('type', filters.type);
      if (filters.startTime) queryParams.append('startTime', filters.startTime);
      if (filters.endTime) queryParams.append('endTime', filters.endTime);

      // 如果是礼物消息类型，使用礼物统计API
      const url = filters.type === 'WebcastGiftMessage' 
        ? `/api/gifts/stats/summary${queryParams.toString() ? '?' + queryParams.toString() : ''}` 
        : `/api/messages/stats${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
        
      const response = await api.get(url);
      
      if (response.success) {
        // 如果是礼物统计，需要适配统计数据格式
        if (filters.type === 'WebcastGiftMessage') {
          const giftStats = response.data as {
            totalGifts: number;
            totalValue: number;
            uniqueUsers: number;
            topGifts: Array<{
              giftName: string;
              giftIcon: string;
              totalQuantity: number;
              totalValue: number;
            }>;
          };
          
          // 将礼物统计数据转换为消息统计格式
          const messageStats: MessageStats = {
            totalMessages: giftStats.totalGifts || 0,
            messagesByType: {
              gift: giftStats.totalGifts || 0,
              chat: 0
            },
            topGifts: (giftStats.topGifts || []).map(gift => ({
              giftName: gift.giftName,
              count: gift.totalQuantity,
              totalValue: gift.totalValue
            })),
            activeUsers: new Array(giftStats.uniqueUsers || 0).fill({
              userName: '礼物赠送用户',
              messageCount: 1
            })
          };
          
          setStats(messageStats);
        } else {
          setStats(response.data as MessageStats);
        }
      } else {
        message.error('获取消息统计失败');
      }
    } catch (error) {
      console.error('获取消息统计错误:', error);
      if (error instanceof ApiError) {
        message.error(`获取消息统计失败: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
    }
  }, []);

  // 删除消息
  const deleteMessage = useCallback(async (messageId: string) => {
    try {
      const response = await api.delete(`/api/messages/${messageId}`);
      
      if (response.success) {
        message.success(MESSAGES.SUCCESS.DELETE);
        // 重新获取消息列表
        await fetchMessages();
        return true;
      } else {
        message.error('删除消息失败');
        return false;
      }
    } catch (error) {
      console.error('删除消息错误:', error);
      if (error instanceof ApiError) {
        message.error(`删除消息失败: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.DELETE);
      }
      return false;
    }
  }, [fetchMessages]);

  return {
    messages,
    loading,
    pagination,
    stats,
    fetchMessages,
    fetchMessageStats,
    deleteMessage,
  };
};